import { Form, message } from 'antd';
import { useState } from 'react';

import { useRequest, useSetState } from '@szzj/hooks';

import { addAuth, getUserByMobile, getUserDetail, updateAuth } from '@/services/permission/user';

import useAppCode from './useAppCode';

import type { IUserDetail, IUserItem } from '@/types/permission/user';

export interface IAuthFormData {
  mobile: string;
  authList: {
    deletedIndex?:boolean;
    deptCode: string;
    roleList: string[];
  }[];
}

export default function useEdit() {
  const { appCode, userAppCode } = useAppCode();

  const [editForm] = Form.useForm();
  const [modal, setModal] = useSetState<{
    open: boolean;
    isEdit: boolean;
    loading: boolean;
    data: IUserDetail | null;
  }>({
    open: false,
    isEdit: false,
    loading: false,
    data: null,
  });
  const [deptRoleRequests, setDeptRoleRequests] = useState<IUserDetail['deptRoleRequests']>([]);

  // 保存
  const saveReq = useRequest(addAuth, {
    manual: true,
  });

  // 更新
  const updateReq = useRequest(updateAuth, {
    manual: true,
  });

  /**
   * 设置初始角色配置
   * @param deptRoleRequests
   */
  const setInitialValues = (deptRoleRequests: IUserDetail['deptRoleRequests']) => {
    setDeptRoleRequests(deptRoleRequests);

    const authList: IAuthFormData['authList'] = [];
    deptRoleRequests?.forEach((item) => {
      authList.push({
        deletedIndex: item.deletedIndex,
        deptCode: item.deptCode,
        roleList: item.roleList?.map((role) => role.roleCode),
      });
    });

    editForm.resetFields();
    editForm.setFieldsValue({ authList });
  };

  /**
   * 电话号码进行查询，只在新增态使用
   * @param mobile
   */
  async function onSearch(mobile: number) {
    setModal({
      open: true,
      isEdit: false,
      loading: true,
    });
    const res = await getUserByMobile({
      mobile,
      appCode,
      userAppCode,
    });

    if (res.success) {
      setModal({
        loading: false,
        isEdit: false,
        data: res.data,
      });

      const { deptRoleRequests } = res.data;
      setInitialValues(deptRoleRequests);
    } else {
      setModal({
        loading: false,
        data: null,
      });
    }
  }

  // 打开编辑or新增框
  async function onOpen(data: IUserItem | null, isEdit = true) {
    if (isEdit && data) {
      setModal({
        isEdit,
        open: true,
      });
      if (!data.id) return;

      const res = await getUserDetail({
        id: data.id,
        appCode,
        userAppCode,
      });

      if (res.success) {
        setModal({
          loading: false,
          data: res.data,
        });

        const { deptRoleRequests } = res.data || {};
        setInitialValues(deptRoleRequests);
      }
    } else {
      setModal({
        open: true,
        isEdit,
        loading: false,
      });
      editForm.resetFields();
    }
  }
  // 关闭编辑or新增框
  function onClose() {
    setModal({
      open: false,
      isEdit: true,
      loading: true,
      data: null,
    });
  }

  // 提交
  async function onSubmit() {
    const values: IAuthFormData = await editForm.validateFields();
    const { authList, mobile: mobileField } = values;
    const deptRoleRequests = authList.map((item) => ({
      deptCode: item.deptCode,
      roleList: item.roleList.map((roleCode) => ({
        roleCode,
      })),
    }));

    if (modal.data?.id) {
      const res = await updateReq.runAsync({
        deptRoleRequests,
        id: modal.data?.id,
        appCode,
        userAppCode,
        mobile: mobileField,
      });
      if (res.success) {
        onClose();
        message.success('保存成功！');
      }
      return res;
    } else {
      const res = await saveReq.runAsync({
        deptRoleRequests,
        mobile: modal?.data?.mobile,
        userCode: modal?.data?.userCode,
        appCode,
        userAppCode,
      });
      if (res.success) {
        onClose();
        message.success('新增用户成功！');
      }
      return res;
    }
  }

  return {
    modal,
    editForm,
    submitLoading: updateReq.loading || saveReq.loading,
    onOpen,
    onClose,
    onSubmit,
    onSearch,
    deptRoleRequests,
  };
}
